import socket
import time

from absl import app, flags

from coin.exchange.kr_rest.feed.ws_feed_impl import generate_ws_feed_client
from coin.exchange.base.kr_ws.ws_parser_base import (WsFeedPrinter, WsFeedArchiver)

FLAGS = flags.FLAGS

flags.DEFINE_string('exchange', None, 'exchange name')
flags.DEFINE_string('api_version', None, 'api_version')
flags.DEFINE_string('product', None, 'product')
flags.DEFINE_string('filename', None, 'filename')
flags.DEFINE_bool('verbose', None, 'verbose')


def main(_):
  feed = generate_ws_feed_client("Spot",
                                 FLAGS.exchange,
                                 FLAGS.api_version,
                                 FLAGS.product,
                                 WsFeedPrinter())

  if FLAGS.filename is not None:
    filename = FLAGS.filename
  else:
    filename = "data/%s.%s.%s.%s.%d" % (FLAGS.exchange,
                                        FLAGS.api_version,
                                        str(feed.getRequest().product),
                                        socket.gethostname(),
                                        int(time.time()))

  print("saving to " + filename)

  feed.set_feed_handler(WsFeedArchiver(filename=filename, verbose=FLAGS.verbose))

  feed.start()
  feed.printInfo()
  while True:
    print("RecvMsgCount =", "%i" % feed.getRecvMsgCount())
    time.sleep(1)
  feed.stop()


if __name__ == '__main__':
  app.run(main)
